// localStorage 长久存储

// cookie 存储

//    两个    一个七天   正常使用    一个30秒  刚测试用     目前一切正常

// 设置 cookie，默认存储7天
export const setCookie = function (cookieName, value, days = 7) {
  const expirationDate = new Date()
  expirationDate.setDate(expirationDate.getDate() + days)
  const cookieValue = encodeURIComponent(value) + '; expires=' + expirationDate.toUTCString() + '; path=/'
  document.cookie = cookieName + '=' + cookieValue
}

// 设置 cookie，过期时间为 30 秒
// export const setCookie = function (cookieName, value, seconds = 30) {
//     const expirationDate = new Date();
//     expirationDate.setTime(expirationDate.getTime() + (seconds * 1000));
//     const cookieValue = encodeURIComponent(value) + "; expires=" + expirationDate.toUTCString() + "; path=/";
//     document.cookie = cookieName + "=" + cookieValue;
// }

export function getCookie(cookieName) {
  const name = cookieName + '='
  const decodedCookie = decodeURIComponent(document.cookie)
  const cookieArray = decodedCookie.split(';')
  for (let i = 0; i < cookieArray.length; i++) {
    let cookie = cookieArray[i].trim()
    if (cookie.indexOf(name) === 0) {
      let cookieValue = cookie.substring(name.length, cookie.length)
      let expiration = getCookieExpiration(cookie)
      if (expiration && new Date(expiration) < new Date()) {
        deleteCookie(cookieName)
        return null
      }
      return cookieValue
    }
  }
  return null
}

function getCookieExpiration(cookie) {
  let parts = cookie.split(';')
  for (let part of parts) {
    part = part.trim()
    if (part.startsWith('expires=')) {
      return part.substring(8)
    }
  }
  return null
}

// 删除 cookie
export const deleteCookie = (cookieName) => {
  document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
}
